import styles from './index.module.scss'
import { Button, message, Space, Input } from 'antd'
import { useState, useCallback, useMemo } from 'react'
import { nanoid } from 'nanoid'
import ajax from './utils/ajax'
import download from './utils/download'
import Login from './Login'
import { useDrag } from './hooks/useDrag'

const App = () => {
  const createItem = () => {
    return {
      id: nanoid(),
      loading: false,
      url: '',
      content: {}
    }
  }
  const [ loading, setLoading ] = useState<boolean>(false)
  const [data, setData] = useState<any[]>([createItem()])
  const { handleDragStart,
    handleDragOver,
    handleDragEnter,
    handleDragEnd, } = useDrag(data, setData, { spec: null })
  const handleChangeUrl = useCallback((e: any) => {
    const _index = Number(e.target.dataset.index)
    const value = e.target.value
    setData((vals) => {
      return vals.map((item, index) => {
        if(index === _index) {
          item.url = value
        }
        return item
      })
    })
  }, [])
  // 修改标题
  const handleChangeTitle = useCallback((e: any) => {
    const _index = Number(e.target.dataset.index)
    const value = e.target.value
    setData((vals) => {
      return vals.map((item, index) => {
        if(index === _index) {
          item.content.cn_title = value
        }
        return item
      })
    })
  }, [])
  const handleChangeContent = useCallback((e: any) => {
    const _index = Number(e.target.dataset.index)
    const value = e.target.value
    setData((vals) => {
      return vals.map((item, index) => {
        if(index === _index) {
          item.content.cn_summary = value
        }
        return item
      })
    })
  }, [])
  // 修改摘要
  const handleAction = useCallback((type: string, e?: any) => {
    switch(type) {
      case 'add':
        const newData = [...data]
        newData.splice(e + 1, 0, createItem())
        setData(newData)
        break
      case 'del':
        const _index = Number(e.target.dataset.index)
        setData(vals => {
          return vals.filter((_, index) => index !== _index)
        })
        break
      case 'search':
        const item = data[e]
        if (!item.url) {
          message.warning('请先添加url')
          return false
        }
        setData((vals) => {
          return vals.map((item, index) => {
            if (index === e) {
              item.loading = true
            }
            return item
          })
        })
        ajax.get(`/get_text?url=${item.url}`).then(res => {
          setData((vals) => {
            return vals.map((item, index) => {
              if (index === e) {
                item.content = res.data
              }
              return item
            })
          })
        }).catch(err => {
          console.log(err)
          if (err.response.status === 401 || err.response.status === 403) {
            if (err.response.status === 401) {
              message.warning(`${err.response.data.cn_title},请先登录`)
            }
            setData((vals) => {
              return vals.map((item, index) => {
                if (index === e) {
                  item.content = err.response.data
                }
                return item
              })
            })
          }
        }).finally(() => {
          setData((vals) => {
            return vals.map((item, index) => {
              if (index === e) {
                item.loading = false
              }
              return item
            })
          })
        })
        break
      case 'download':
        const params = data.filter(item => Object.keys(item.content).length).map(item => item.content)
        if (params.length < 1) {
          message.warning('请先添加url')
          return false
        }
        setLoading(true)
        ajax.post('/get_word', {
          data: params,
        }).then(res => {
          download(`/api/download?file_name=${res.data.file_name}`, res.data.file_name)
          setLoading(false)
        }).finally(() => {
          setLoading(false)
        })
        break
    }
  }, [data])

  return (
    <section className={styles.container}>
      <header className={styles.header}>
        <Space>
          <Button type="primary" loading={loading} onClick={() => handleAction('download')}>下载word</Button>
          <Login />
        </Space>
      </header>
      {
        data.map((item, index) => {
          return <section draggable style={{ cursor: 'move' }} onDragStart={handleDragStart} onDragEnter={handleDragEnter} onDragOver={handleDragOver} onDragEnd={handleDragEnd} data-id={item.id} key={item.id} className={styles.item}>
            {
              'spec' in item ? <section className='spec' style={{ minHeight: '80px', background: '#f1f1f1' }}></section> : <section>
              <div className='action'>
                <span style={{ borderRight: index === 0 ? '1px solid #f1f1f1' : 'none' }} onClick={() => handleAction('add', index)}>+</span>
                {
                  index>=1 ? <span data-index={index} onClick={(e) => handleAction('del', e)}>-</span> : null
                }
              </div>
              <div className='flex mb10'>
                <Input placeholder='请输入网址' data-index={index} value={item.url} onChange={handleChangeUrl}/>
                <Button style={{ margin: '0 0 0 15px' }} loading={item.loading} type="primary" onClick={() => handleAction('search', index)}>查询</Button>
              </div>
              {
                Object.keys(item.content).length ? <section style={{width: 'calc(100% - 80px)'}}>
                  <div style={{color: '#999', marginBottom: 5}}>结果：</div>
                  <div style={{marginBottom: 15}}>
                    <Input value={item.content.cn_title} data-index={index} onChange={handleChangeTitle} />
                  </div>
                  {
                    item.content.cn_summary ? <section>
                      <Input.TextArea value={item.content.cn_summary} rows={5} data-index={index} style={{color: '#666'}} onChange={handleChangeContent}></Input.TextArea>
                    </section> : null
                  }
                </section> : null
              }
              </section>
            }
          </section>
        })
      }
    </section>
  )
}

export default App
